#include "StdAfx.h"
#include "DbService.h"
#include "sqlite3.h"

CDbService::CDbService(void)
{
}

CDbService::~CDbService(void)
{
}

const _TUCHAR* CDbService::query(TCHAR* dbFile, TCHAR* field, TCHAR* value, TCHAR* returnedField)
{
	sqlite3 *database;
	sqlite3_stmt *preparedStatement;
	const TCHAR *tail;
	TCHAR* trimedField;
	if (field[_tcslen(field)] == ' ')
	{
		trimedField = new TCHAR [_tcslen(field) - 1];
		_tcsncpy(trimedField,field,_tcslen(field) - 1);
	}
	else
	{
		trimedField = field;
	}

	TCHAR* sqlStr = {""};
	sqlite3_open(dbFile, &database);
	int iResult = sqlite3_prepare(database,sqlStr, _tcslen(sqlStr),&preparedStatement,&tail);
	int sqliteStep = sqlite3_step(preparedStatement);
	const TCHAR* columnName;
	const _TUCHAR* columnValue;
	if (iResult == SQLITE_OK &&  sqliteStep == SQLITE_ROW)
	{
		int columnCount = sqlite3_column_count(preparedStatement);
		for (int ii = 0; ii < columnCount; ii++)
		{
			columnName = sqlite3_column_name(preparedStatement,ii);			
			if (_tcscmp(columnName,returnedField)== 0)
			{
				columnValue = sqlite3_column_text(preparedStatement,ii);
				break;
			}
			
		}
	}
	sqlite3_finalize(preparedStatement);
	sqlite3_close(database);	
	return columnValue;
}
